from django import template
from django.template import Node, NodeList, Template, Context, Variable, VariableDoesNotExist
from django.template.defaulttags import IfEqualNode

import django_widgets.template_helpers as template_helpers

register = template.Library()

@register.tag(name="overlay")
def do_add_overlay(parser,  token):
    try:
        tag,  link_id = token.split_contents()
        prefix = None
    except ValueError:
        try:
            tag,  prefix,  link_id = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError,  "%r tag requires one or two arguments" % token.contents.split()[0]
    return AddOverlay(link_id,  prefix)

class AddOverlay(template.Node):
    def __init__(self,  link_id,  prefix):
        self.link_id = link_id
        self.prefix = prefix
    def render(self,  context):
        if self.prefix:
            link_id = "%s%s" % (str(self.prefix),  str(template_helpers.resolve_variable(self.link_id,  context)))
        else:
            link_id = self.link_id
        ajax_script = "<script type='text/javascript'>" + \
                                    '$("#' + str(link_id) + \
                                    '").overlay();' +\
                                "</script>"
        return_value = "\n" + ajax_script + "\n"
        return return_value
        
@register.tag(name="close_onclick")
def do_close_onclick(parser,  token):
    try:
        tag,  box_id = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError,  "%r tag requires one argument" % token.contents.split()[0]
    return CloseOnClick(box_id)

class CloseOnClick(template.Node):
    """
    link_id - id of the link to attach this ajax event
    box_id - id of the check login box
    """
    
    def __init__(self,  box_id):
        self.box_id = box_id
    def render(self,  context):
        ajax_script = "<script type='text/javascript'>" + \
                                    '$("#' + str(self.box_id) + \
                                    '").bind("click", function() {close_box("' + str(self.box_id)  + '");});' +\
                                "</script>"
        return_value = "\n" + ajax_script + "\n"
        return return_value
